﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kz.Telegram.Bot.Infrastructure.Helpers
{
    public class CMDHelper
    {
        /// <summary>
        /// 执行CMD任务  返回是否完成
        /// </summary>
        /// <param name="command">执行语句</param>
        /// <param name="timeout">超时时间  毫秒</param>
        /// <returns></returns>
        public static bool CmdReturnBool(string command, int timeout)
        {
            try
            {
                Process p = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = @"C:\windows\system32\cmd.exe";
                startInfo.Arguments = @"/C " + command;
                startInfo.RedirectStandardError = true;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardInput = true;
                p.StartInfo = startInfo;
                if (!p.Start())
                {
                    Console.WriteLine("Error starting");
                }
                p.BeginErrorReadLine();//开始异步读取
                var isEnd = p.WaitForExit(timeout);//阻塞等待进程结束
                Console.WriteLine(isEnd);
                p.StandardInput.WriteLine("q");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error {ex.Message}");
                return false;
            }

        }

        /// <summary>
        /// 获取视频流信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetMediaInfo(string input)
        {
            try
            {
                Process p = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                string command = $"ffprobe -v quiet -print_format json -show_format -show_streams -print_format json {input}";
                startInfo.FileName = @"C:\windows\system32\cmd.exe";
                startInfo.Arguments = @"/C " + command;
                startInfo.RedirectStandardError = true;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardInput = true;
                p.StartInfo = startInfo;
                if (!p.Start())
                {
                    Console.WriteLine("Error starting");
                }
                string frames = p.StandardOutput.ReadToEnd();

                var info = frames;
                p.Kill();
                return info;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
    }
}
